// store/auth.js
import { defineStore } from 'pinia'
import api from '@/utils/api'
import {
  setToken,
  getToken,
  removeToken,
  setUserInfo,
  getUserInfo,
  removeUserInfo,
  setTokenExpiry,
  getTokenExpiry,
  removeTokenExpiry
} from '@/utils/auth'

/* ----------  API 封装 ---------- */
export const login = (credentials) =>
  api.post('/api/users/login', credentials)
    .then(res => res)
    .catch(error => ({
      code: error.response?.status || 500,
      msg: error.response?.data?.msg || error.message,
      data: null
    }))

export const register = (credentials) =>
  api.post('/api/users/register', credentials)
    .then(res => res)
    .catch(error => ({
      code: error.response?.status || 500,
      msg: error.response?.data?.msg || error.message,
      data: null
    }))

export const logout = () =>
  api.post('/api/users/logout', null, {
    headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
  })
    .then(res => {
      const backendResponse = res.data
      return {
        code: backendResponse.code || 200,
        msg: backendResponse.msg || '登出成功',
        data: backendResponse.data || null
      }
    })
    .catch(() => ({ code: 200, msg: '登出成功', data: null }))

export const getCurrentUser = (id) => {
  if (!id) return Promise.reject(new Error('缺少用户ID'))
  return api.get(`/api/users/${id}`)
    .then(res => {
      const backendResponse = res.data
      if (backendResponse.code !== 200) {
        throw new Error(backendResponse.msg || '无效响应数据')
      }
      const userData = backendResponse.data?.user || backendResponse.data
      if (!userData) throw new Error('未找到用户信息')
      return {
        id: userData.id,
        username: userData.username,
        nickname: userData.nickname,
        email: userData.email,
        avatarUrl: userData.avatarUrl,
        bio: userData.bio,
        followingCount: userData.followingCount || 0,
        followersCount: userData.followersCount || 0,
        notesCount: userData.notesCount || 0,
        createdAt: userData.createdAt,
        updatedAt: userData.updatedAt
      }
    })
    .catch(error => {
      if (error.response?.status === 404) throw new Error('用户不存在')
      throw error
    })
}

export const updateUser = async (id, data) => {
  try {
    const res = await api.put(`/api/users/${id}`, data)
    const backendResponse = res.data
    return {
      code: backendResponse.code || 200,
      msg: backendResponse.msg || '更新成功',
      data: backendResponse.data || null
    }
  } catch (error) {
    return {
      code: error.response?.status || 500,
      msg: error.response?.data?.msg || error.message || '服务器异常',
      data: null
    }
  }
}

export const updatePwd = async (id, { oldPassword, newPassword }) => {
  try {
    const res = await api.patch(`/api/users/${id}/password`, { oldPassword, newPassword })
    const backendResponse = res.data
    return {
      code: backendResponse.code || 200,
      msg: backendResponse.msg || '密码更新成功',
      data: backendResponse.data || null
    }
  } catch (error) {
    return {
      code: error.response?.status || 500,
      msg: error.response?.data?.msg || error.message || '服务器异常',
      data: null
    }
  }
}

/* ----------  Store 定义 ---------- */
export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: getUserInfo(),
    token: getToken(),
    tokenExpiry: getTokenExpiry(),
    isAuthenticated: !!getToken(),
    isLoading: false,
    error: null
  }),

  actions: {
    /* 登录 */
    async login(credentials) {
      this.isLoading = true
      this.error = null
      try {
        const res = await login(credentials)
        if (res.code !== 200) throw new Error(res.msg || '登录失败')

        const { token, user: userData, expiresIn } = res.data || {}
        if (!token) throw new Error('服务器未返回 token')
        if (!userData) throw new Error('服务器未返回用户信息')

        this.token = token
        this.isAuthenticated = true
        setToken(token)

        const expiryTimestamp = Date.now() + expiresIn * 1000
        this.tokenExpiry = expiryTimestamp
        setTokenExpiry(expiryTimestamp)

        this.user = {
          id: userData.id,
          username: userData.username,
          nickname: userData.nickname,
          email: userData.email,
          avatarUrl: userData.avatarUrl,
          bio: userData.bio,
          followingCount: userData.followingCount || 0,
          followersCount: userData.followersCount || 0,
          notesCount: userData.notesCount || 0,
          createdAt: userData.createdAt,
          updatedAt: userData.updatedAt
        }
        setUserInfo(this.user)

        // 建立 WebSocket 连接
        import('@/utils/webSocket').then(ws => ws.default.initConnection())

        return { success: true, user: this.user }
      } catch (e) {
        this.error = e.message
        return { success: false, message: e.message }
      } finally {
        this.isLoading = false
      }
    },

    /* 刷新 Token */
    async refreshToken() {
      if (!this.token) return false
      try {
        const res = await api.post('/api/users/refresh', {}, {
          headers: { Authorization: `Bearer ${this.token}` }
        })
        if (res.code !== 200) throw new Error(res.msg || '刷新 Token 失败')

        const { token: newToken, expiresIn } = res.data
        this.token = newToken
        setToken(newToken)

        const expiryTimestamp = Date.now() + expiresIn * 1000
        this.tokenExpiry = expiryTimestamp
        setTokenExpiry(expiryTimestamp)
        return true
      } catch (error) {
        console.error('刷新 Token 失败:', error)
        this.logout()
        return false
      }
    },

    /* 判断是否即将过期 */
    isTokenExpiringSoon() {
      if (!this.tokenExpiry) return false
      return this.tokenExpiry - Date.now() < 5 * 60 * 1000
    },

    /* 登出 */
    async logout() {
      this.isLoading = true
      try {
        await logout()
      } finally {
        this.clearAuthData()
        import('@/utils/webSocket').then(ws => ws.default.disconnect())
        this.isLoading = false
      }
      return true
    },

    /* 更新个人资料（信息 + 密码） */
    async updateProfile({ userDto, pwdDto }) {
      try {
        const userId = this.user?.id
        if (!userId) throw new Error('用户未登录')

        // 更新基本信息
        const userRes = await updateUser(userId, userDto)
        if (userRes.code !== 200) throw new Error(userRes.msg || '更新用户信息失败')

        // 更新密码
        if (pwdDto) {
          const pwdRes = await updatePwd(userId, pwdDto)
          if (pwdRes.code !== 200) throw new Error(pwdRes.msg || '更新密码失败')
        }

        // 重新拉取最新用户数据
        const updatedUser = await getCurrentUser(userId)
        this.user = updatedUser
        setUserInfo(updatedUser)
        return { success: true }
      } catch (error) {
        console.error('更新个人资料失败:', error)
        return { success: false, message: error.message }
      }
    },

    /* 清空登录态 */
    clearAuthData() {
      this.user = null
      this.token = null
      this.tokenExpiry = null
      this.isAuthenticated = false
      removeToken()
      removeUserInfo()
      removeTokenExpiry()
    }
  }
})